import React,{useState,createContext} from 'react'
import classNames from 'classnames'
import {MenuItemProps} from './menuItem'

type MenuMode = 'horizontal' | 'vertical'; //水平(横向) 垂直(纵向)
export interface MenuProps{
    /**
   * 默认高亮的index
   * @default
   */
    defaultIndex?:string;  
      /**
   * 自定义的className
   * @default
   */
    className?:string;  
        /**
   * 渲染模式
   * @default
   */
    mode?:MenuMode;
        /**
   * 样式
   * @default
   */
    style?:React.CSSProperties;
        /**
   * 选择的点击事件
   * @default
   */
    onSelect?:(selectedIndex:string)=>void;
    /**
   * 子节点
   * @default
   */
    children?:any
        /**
   * 默认展开子菜单
   * @default
   */
    defaultOpenSubMenus?:string[];
}
//使用context，实现跨组件传参
interface IMenuContext {
    index:string;
    onSelect?:(selectedIndex:string)=>void;
    mode?:MenuMode
    defaultOpenSubMenus?:string[];
}
 
export const MenuContext = createContext<IMenuContext>({index:'0'})
const Menu:React.FC<MenuProps> = (props) =>{
    const {className,mode,style,children,defaultIndex,onSelect,defaultOpenSubMenus} = props
    const [currentActive,setActive]  = useState(defaultIndex)
    const classes = classNames('viking-menu',className,{
        'menu-vertical':mode === 'vertical',
        'menu-horizontal':mode !== 'vertical',
    })
    const handleClick = (index:string) =>{
        setActive(index)
        if(onSelect){
            onSelect(index)
        }
    }
    const passedContext:IMenuContext = {
        index:currentActive?currentActive:'0',
        onSelect:handleClick,
        mode:mode,
        defaultOpenSubMenus
    }
    const renderChildren = () =>{
        return React.Children.map(children,(child,index)=>{
            const childElement = child as React.FunctionComponentElement<MenuItemProps>;
            const {displayName} = childElement.type 
            if(displayName === 'MenuItem'||displayName === 'SubMenu'){
                return React.cloneElement(childElement,{
                    index:index.toString()
                })
            }else {
                console.error("Warning:Menu has a child which is not a MenuItem component")
            }
        })
    }
    return (
        <ul className={classes} style={style} data-testid="test-menu">
            <MenuContext.Provider value={passedContext}>
            {renderChildren()}
            </MenuContext.Provider>
        </ul>
    )
}
//默认属性
Menu.defaultProps = {
    defaultIndex:'0',
    mode:'horizontal',
    defaultOpenSubMenus:[]
}

export default Menu